package dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnectionPool extends ObjectsPool<Connection> {
	private Properties properties;

	public DBConnectionPool() throws IOException {
		this.loadProperties();
		try {
			Class.forName(properties.getProperty("driver")).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected Connection create() {
		try {
			return (DriverManager.getConnection(properties.getProperty("url"), properties
					.getProperty("user"), properties.getProperty("password")));
		} catch (SQLException e) {
			e.printStackTrace();
			return (null);
		}
	}

	@Override
	public void expirate(Connection o) {
		try {
			o.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean validate(Connection o) {
		try {
			return !(o.isClosed());
		} catch (SQLException e) {
			e.printStackTrace();
			return (false);
		}
	}

	public Connection getConnection() {
		return super.checkOut();
	}

	public void returnConnection(Connection c) {
		super.checkIn(c);
	}

	private void loadProperties() throws IOException {
		properties = new Properties();
		properties.load(getClass().getResourceAsStream("/database.properties"));
	}
}
